#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <sys/msg.h>
#include "shell.h"

void *ShellClient(void *arg)
{
    int msgId;
    ShellCmd cmd;

    printf("Welcome to shell!\n"
           "You can input some function name to execute.\n"
           "Input \"exit\" to exit this shell.\n"
           "Input \"kill\" to kill the shell server!\n");

    msgId = msgget((key_t)MSG_QUEUE_KEY, 0666 | IPC_CREAT);
    if (msgId == -1) {
        printf("Create msg queue failed\n");
        goto _exit;
    }

    cmd.type = 1;
    while (1) {
        printf("> ");
        memset(cmd.cmd, 0, BUFSIZ);
        fgets(cmd.cmd, BUFSIZ, stdin);
        if (strncmp(cmd.cmd, "exit", 3) == 0) {
            goto _exit;
        }
        if (msgsnd(msgId, (void *)&cmd, BUFSIZ, 0) == -1) {
            printf("Send to msg queue failed, %s\n", strerror(errno));
            break;
        }
    }

_exit:
    pthread_exit(0);
}

int main(int argc, char *argv[])
{
    pthread_t tid = 0;
    int ret;

    ret = pthread_create(&tid, NULL, ShellClient, NULL);
    if (ret != 0) {
        printf("Create shell client thread faild\n");
    }
    pthread_join(tid, NULL);

    return 0;
}
